/*
    Kelompok    2
    Kelas       2
    Anggota :
    1. Yudha Wastu Prawira      / 13509002
    2. Robertus Theodore        / 13509008
    3. Rendy Bambang Junior     / 13509036
    4. Hartono Sulaiman Wijaya  / 13509046
    5. Daniel Prihartoni        / 13509088
    6. Raydhitya Yosep          / 13509092

*/


#include "App.h"

//inisialisasi pointer global
App* p_App = NULL;

//ctor, mengosongkan variable-variable
App::App(){
	p_Input = NULL;
	p_Display = NULL;
	while(!stackOfStates.empty()){
		remState();
	}
	endOfApp = false;
}

//dtor, mendelete pointer2 yang telah di buat dan membersihkan stack
App::~App(){
	delete p_Input;
	delete p_Display;
	while(!stackOfStates.empty()){
		remState();
	}
}

//membuat parser input dan display baru
void App::initialize(){
	p_Input = new Parser();
	p_Display = new Display();
	p_Input->mode = COMMAND_MODE;
}

//jalan program utama disini. state di bersihkan dan input diterima lalu diproses dan ditampilkan
void App::update(){
	bool activeStateFound = false;
	//cari state yang aktif. bila ketemu yang tidak aktif, di remove
	while(!activeStateFound && !stackOfStates.empty()){
		if (stackOfStates.top()==NULL)
			stackOfStates.pop();
		else
			if (stackOfStates.top()->isActive()){
				activeStateFound = true;
			}
			else
				remState();
	}
	//program utama berjalan disini, input -> proses -> tampil
	if(!stackOfStates.empty())
		p_Display->draw(stackOfStates.top()->update(p_Input->update()));
	else
		endOfApp = true;
}

//untuk menambah state baru ke stack
void App::addState(State * state){
	//tambahkan state ke stackOfStates
	stackOfStates.push(state);
}

//membuang state atas dan menginisialisasi state dibawahnya (bila ada)
void App::remState(){
	//Destruct dan buang state dari stack
	delete stackOfStates.top();
	stackOfStates.pop();
	if(!stackOfStates.empty())
		if(stackOfStates.top()->isActive())
			p_Display->draw(stackOfStates.top()->getFirstDisplay());
}

//mengembalikan tampilan pertama dari state teratas
DisplayInfo App::getFirstDisplay(){
	return stackOfStates.top()->getFirstDisplay();
}

//memberi delay x detik
void App::delay(int x){
	time_t start_time, cur_time;
    time(&start_time);
    do{
	    time(&cur_time);
    }
    while((cur_time - start_time) < x);
}
